<script lang="ts">
  import { Tabs } from "@skeletonlabs/skeleton-svelte";
  import { drawStore } from "../store.svelte";
  import { remove_edge, type DrawEdgeInfo } from "$lib/api/board/board_draw";
  import EditContentPanel from "./EditContentPanel.svelte";
  import { get_user_session } from "$lib/api/user";
  import { request } from "$lib/utils/request";

  const curEdge = $derived(getCurEdge());

  function getCurEdge(): DrawEdgeInfo | undefined {
    if (drawStore.selectEdgeKeyList.length == 0) {
      return undefined;
    }
    const edgeKey = drawStore.selectEdgeKeyList[0];
    return drawStore.edgeList.find(
      (item) =>
        item.edge_key.from_node_id == edgeKey.from_node_id &&
        item.edge_key.from_handle == edgeKey.from_handle &&
        item.edge_key.to_node_id == edgeKey.to_node_id &&
        item.edge_key.to_handle == edgeKey.to_handle
    );
  }

  let curTab = $state("content" as "content" | "remove");

  async function removeEdge() {
    if (curEdge == undefined) {
      return;
    }
    const sessionId = await get_user_session();
    await request(
      remove_edge({
        session_id: sessionId,
        board_id: drawStore.boardInfo?.board_id ?? "",
        draw_id: drawStore.drawId,
        edge_key: curEdge.edge_key,
      })
    );
    drawStore.removeSelectEdgeKey(curEdge.edge_key);
  }
</script>

{#if curEdge != undefined}
  <div class="bg-surface-200-800 w-[250px] p-1 pb-4">
    <Tabs
      value={curTab}
      onValueChange={(detail) =>
        (curTab = detail.value as "content" | "remove")}
    >
      {#snippet list()}
        <Tabs.Control value="content">内容</Tabs.Control>
        <Tabs.Control value="remove">删除</Tabs.Control>
      {/snippet}

      {#snippet content()}
        <Tabs.Panel value="content">
          <div class="max-h-[calc(100vh-400px)] overflow-y-auto">
            <EditContentPanel edge={curEdge} />
          </div>
        </Tabs.Panel>

        <Tabs.Panel value="remove">
          {#if curTab == "remove"}
            <div class="flex items-center justify-center">
              <button
                type="button"
                class="btn preset-filled-error-900-100"
                onclick={() => removeEdge()}>删除连线</button
              >
            </div>
          {/if}
        </Tabs.Panel>
      {/snippet}
    </Tabs>
  </div>
{/if}
